<template>
  <div>
    <a-modal
      :maskClosable="false"
      title="重置密码"
      v-if="visible"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout">
        <a-form-model-item has-feedback label="新的密码" prop="pass">
          <a-input v-model="ruleForm.pass" type="password" autocomplete="off" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="核对密码" prop="checkPass">
          <a-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>

import { reSetPwd } from '@/api/system/user'

export default {
  components: { },
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新的密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      confirmLoading: false,
      ruleForm: {
        pass: '',
        checkPass: ''
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'change' }],
        checkPass: [{ validator: validatePass2, trigger: 'change' }]
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 }
      }
    }
  },
  methods: {
    init () {
      this.visible = true
    },
    show () {
      this.visible = true
    },
    handleCancel () {
      this.ruleForm.pass = ''
      this.ruleForm.checkPass = ''
      this.resetForm('ruleForm')
      this.visible = false
    },
    handleOk () {
      this.submitForm('ruleForm')
    },
    setPwd () {
      const params = {
        newPassWord: this.ruleForm.pass
      }

      reSetPwd(params).then(res => {
        if (res.code === 200) {
          this.visible = false
          this.$success({
            title: '通知',
            content: '密码重置成功!'
          })
        } else {
          this.$error({
            title: '通知',
            content: res.msg || '密码重置失败'
          })
        }
      }).catch(() => {
        this.$error({
          title: '通知',
          content: '操作失败，请检查接口'
        })
      })
    },

    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.setPwd()
        } else {
          console.log('验证失败!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
